<?php

namespace app\index\controller;
use app\admin\library\Auth;
use app\common\controller\Frontend;
use EasyWeChat\Factory;
use app\admin\model\Admin;
use app\common\controller\Api;
use app\common\library\Upload;
use think\Db;
use fpdf\Fpdf;
use fpdi\Fpdi;
use app\admin\model\Recruitto as recru;
use think\Session;
class Recruitto extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    public $config = [
        'app_id' => 'wxdbff4603979f3a42',
        'secret' => '05ada3ffed989618e16672ca338e8444',
        'oauth' => [
            'scopes'   => ['snsapi_userinfo'],
            'callback' => '/index/recruitto/oauth',
        ]
    ];
    public $url_img = ROOT_PATH.'public/pdf/';
    public $type_img = [
                        1=>['name1'=>'1赋能妈妈.pdf','name2'=>'2全部.pdf','name3'=>'3打印用.pdf'],
                    ];
    public $arr_local = [
        //姓名
        'name'=>['size'=>13,'local'=>[42,107.5],'page'=>1],
        //电话
        'tel'=>['size'=>13,'local'=>[49,118],'page'=>1],
        //签字
        'sign_url'=>['size'=>20,'local'=>[42,173],'page'=>2],
        //签订日期
        'sign_date'=>['size'=>13,'local'=>[49,192.5],'page'=>2],
    
      ];

   /**
     * 公共
     * @author gzy
     * @date   2018年8月12日 09:15:00
     */
    public function _initialize(){
        parent::_initialize();
        $this->app = Factory::officialAccount($this->config);
        $this->auth = \app\admin\library\Auth::instance();
        $this->model = new recru;   
        $this->Fpdf = new Fpdf();

    }
    public function oauth()
    {
        $oauth = $this->app->oauth;
        // 获取 OAuth 授权结果用户信息
        $user = $oauth->user();

        $_SESSION['wechat_user'] = $user->toArray();
        Session::set('wechat_user',$user->toArray());
        $targetUrl = empty($_SESSION['target_url']) ? '/' : $_SESSION['target_url'];

        header('location:'. $targetUrl); // 跳转到 user/profile
        return $response = $this->app->oauth->scopes(['snsapi_userinfo'])
            ->redirect();
    }
    /**
     * 生成
     */
    public function generate($source = null){
        if ($this->request->isPost()){
            $params = $this->request->post();
            Db::startTrans();
            $row = $this->model->where('tel','=',$params['tel'])->find();
            if($row && $params){
                if($row['status'] == 2 && $row['contract_url']){
                   Db::rollback();
                   $this->error(__('已经签订,正在跳转','/index/recruitto/question_success/ids/'.$row['id']));
                }
                 $user = Session::get('wechat_user');
                 $row->sign_date = time();
                 $row->openid = $user['id'];
                 $row->url = $user['avatar'];
                 $row->contract_name = $params['name'];
                 $result = $row->save();
                 if($result){
                      Db::commit();
                      $this->success('操作成功','',$row['id']);
                  }else{
                      Db::rollback();
                  }
            }
            Db::rollback();
            $this->error(__('Parameter %s can not be empty', ''));
       }
       if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            $oauth = $this->app->oauth;
            // 未登录
            if (empty($_SESSION['wechat_user'])) {
               if($source){
                 $_SESSION['target_url'] = '/index/recruitto/generate?source='.$source;
               }else{
                 $_SESSION['target_url'] = '/index/recruitto/generate';
               }
//            return $oauth->redirect();
                // 这里不一定是return，如果你的框架action不是返回内容的话你就得使用
                $oauth->redirect()->send();
            }
            // 已经登录过
            $user = $_SESSION['wechat_user'];
            $row = $this->model->where('openid','=',$user['id'])->find();
            if($row){
               if($row['status'] == 2 && $row['contract_url']){
                 $this->error("已经签订,正在跳转",'/index/recruitto/question_success/ids/'.$row['id']);
               }
            }
            $this->app->jssdk->setUrl('');
            $jssdk = $this->app->jssdk->buildConfig(['chooseWXPay'], $debug = false, $beta = false, $json = true);
            $this->view->assign('jssdk',$jssdk);
            $this->view->assign('source',$source);
            return $this->view->fetch();
        }
       return $this->view->fetch('index');
  }  
    /**
     * 生成
     */
    public function handwriting($ids=null){
       if(!$ids)  $this->error('参数错误');
       $row = $this->model->get($ids);
       if(!$row) $this->error('数据不存在');
       if($row['status'] == 2 && $row['contract_url']) $this->error('已经签订,正在跳转','/index/recruitto/question_success/ids/'.$ids);
       if ($this->request->isPost()){
            $params = $this->request->post();
            $info = $row->toArray();
            $info['sign_url'] = $params['sign_url'];
            $info['name'] = $info['contract_name'];
            Db::startTrans();
            if ($params) {
                   $info['sign_date'] = date("Y年m月d日",$info['sign_date']);
                   $resu = $this->watermark($info,1);
                   if($resu['true'] == 1){
                       $params['status'] = 2;
                       $params['contract_url'] = $resu['data'];
                       $result = $row->allowField(true)->save($params);
                        if($result){
                            Db::commit();
                            $this->success('操作成功','','/index/recruitto/question_success/ids/'.$ids);
                        }else{
                            Db::rollback();
                            $this->error('操作失败');
                        }
                   }else{
                      Db::rollback();
                      $this->error('操作失败');
                   }
           
           }
            Db::rollback();
           $this->error('操作失败');
       }
        $this->view->assign("ids", $ids);
       return $this->view->fetch();
   }
    /**
     * 生成
     */
    public function question_success($ids=null){
       if(!$ids)  $this->error('参数错误');
       $row = $this->model->where(['id'=>$ids])->find();
       if(!$row) $this->error('数据不存在');
       if($row['status'] == 1) $this->error('您还没有提交信息','/index/recruitto/generate/');
       /*
        发短信隐藏。
       $info = $row->toArray();
       $info['tel'] = $info['phone'];
       write_log([],'',2,'contract_log');
       $result = send_message(34,[], [$info],'contract_log');*/
       $this->view->assign("row", $row);
       return $this->view->fetch();
   }
  /**
     * 生成苏回音
     */
    public function watermark($arr = [],$type = 1){
        $this->Fpdi = new Fpdi();
            // 设置字体
        $this->Fpdi->AddGBFont('Arial', '宋体');

        // get the page count
        $pageCount = $this->Fpdi->setSourceFile($this->url_img.$this->type_img[$type]['name'.$type]);
              //设置路径目录信息
        $url = ROOT_PATH . 'public/uploads/pdf/'.date("Ymd").'/'.date('YmdHis') . uniqid().'.pdf';  
        $dir_name = dirname($url);
         //目录不存在就创建
        if(!file_exists($dir_name)) {
            //iconv防止中文名乱码
           $res = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
        }
        $imglName = "uploads/pdf/".date("Ymd")."/".date('YmdHis') . uniqid().'.pdf';
       $no_url  = ''.request()->domain().'/'.$imglName.'';
        // iterate through all pages
        for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++)
        {

          // import a page
          $templateId =  $this->Fpdi->importPage($pageNo);

          // get the size of the imported page
          $size =  $this->Fpdi->getTemplateSize($templateId);

          // create a page (landscape or portrait depending on the imported page size)
          if ($size['w'] > $size['h'])  $this->Fpdi->AddPage('L', array($size['w'], $size['h']));
          else  $this->Fpdi->AddPage('P', array($size['w'], $size['h']));
          // use the imported page
           $this->Fpdi->useTemplate($templateId);
          // 只设置第一个pdf页面
           foreach ($arr as $key => $value) {
                  if(isset($this->arr_local[$key]['page'])){
                    if($this->arr_local[$key]['page'] != $pageNo) continue;
                  }
                  switch ($key) {
                   case 'sign_url':
                      // Image参数：文件，x坐标，y坐标，宽，高
                      $this->Fpdi->Image(ROOT_PATH.'public/'.$value,$this->arr_local[$key]['local'][0],$this->arr_local[$key]['local'][1],$this->arr_local[$key]['size'],$this->arr_local[$key]['size']);
                        # code...
                    break;
                    case 'name':
                    case 'tel':
                    case 'sign_date':
                    case 'sign_url':
                          // 设置字体
                         $this->Fpdi->SetFont('Arial', '', $this->arr_local[$key]['size']);
                        // 设置位置
                         $this->Fpdi->SetXY($this->arr_local[$key]['local'][0],$this->arr_local[$key]['local'][1]);
                        // 写入内容
                         $this->Fpdi->Write (7, iconv("utf-8","gbk",$value));
                        # code...
                    break;
                      default:
                    break;
                  }
              }

      }
       $this->Fpdi->Output($imglName);
       return ['true'=>1,'msg'=>'操作成功','data'=>$no_url];
 
    }
    
    public function upload(){
        //是否有图片上传
        if ($this->request->isPost()){
            $params = $this->request->post();
            $upload = new Upload();
            $upload->path(ROOT_PATH.'public/pdf/upload');//上传 发货凭证
            $file = $upload->upbase($params['file'],'/pdf/upload/');
            if($file){
                 $this->success('操作成功','',$file);
            }else{
                 $this->error($upload->error());
            }
        }
    }
    /**
     * 测试
     */
    public function test() {
     $arr = [
        //学生姓名
        'name'=>'郜振宇',
        //电话
        'tel'=>'01092234',
        //签订日期
        'sign_date'=>date('Y年m月d日'),
        //签名
        'sign_url'=>'/pdf/upload/202003231531385e7865da83896.png',
      ];
      $this->Fpdi = new Fpdi();
         // 设置字体
     $this->Fpdi->AddGBFont('Arial', '宋体');

       // get the page count
      $pageCount = $this->Fpdi->setSourceFile($this->url_img.$this->type_img[1]['name1']);
      // iterate through all pages
      for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++)
      {

          // import a page
          $templateId =  $this->Fpdi->importPage($pageNo);

          // get the size of the imported page
          $size =  $this->Fpdi->getTemplateSize($templateId);

          // create a page (landscape or portrait depending on the imported page size)
          if ($size['w'] > $size['h'])  $this->Fpdi->AddPage('L', array($size['w'], $size['h']));
          else  $this->Fpdi->AddPage('P', array($size['w'], $size['h']));

          // use the imported page
           $this->Fpdi->useTemplate($templateId);
            
              foreach ($arr as $key => $value) {
                 if($this->arr_local[$key]['page'] != $pageNo) continue;
                  switch ($key) {
                   case 'sign_url':
                      // Image参数：文件，x坐标，y坐标，宽，高
                      $this->Fpdi->Image(ROOT_PATH.'public/'.$value,$this->arr_local[$key]['local'][0],$this->arr_local[$key]['local'][1],$this->arr_local[$key]['size'],$this->arr_local[$key]['size']);
                        # code...
                    break;
                      default:
                           // 设置字体
                         $this->Fpdi->SetFont('Arial', '', $this->arr_local[$key]['size']);
                        // 设置位置
                         $this->Fpdi->SetXY($this->arr_local[$key]['local'][0],$this->arr_local[$key]['local'][1]);
                        // 写入内容
                         $this->Fpdi->Write (7, iconv("utf-8","gbk",$value));
                    break;
                  }
              }
              // Image参数：文件，x坐标，y坐标，宽，高
              //插入图片
              // Image参数：文件，x坐标，y坐标，宽，高
              // $pdf->Image('timg.jpeg',50,15,44,40);

      }
       $this->Fpdi->Output($this->url_img.'2020赋能妈妈word.pdf');
    }

}
